package la.bbs558.service.impl;

import cn.hutool.core.lang.Snowflake;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import la.bbs558.dao.ExclusiveVisitRecordDao;
import la.bbs558.entity.ExclusiveVisitRecord;
import la.bbs558.entity.UserData;
import la.bbs558.entity.params.ExclusiveVisitRecordPage;
import la.bbs558.entity.params.ExclusiveVisitRecordParams;
import la.bbs558.service.ExclusiveVisitRecordService;
import la.bbs558.service.UserDataService;
import la.bbs558.util.IpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Objects;

/**
 * (ExclusiveVisitRecord)表服务实现类
 *
 * @author Shanks
 * @since 2024-01-19 18:36:32
 */
@Service("exclusiveVisitRecordService")
@Slf4j
public class ExclusiveVisitRecordServiceImpl extends ServiceImpl<ExclusiveVisitRecordDao, ExclusiveVisitRecord> implements ExclusiveVisitRecordService {

    @Resource
    private Snowflake snowflake;

    @Resource
    private UserDataService userDataService;

    @Resource
    private ExclusiveVisitRecordDao exclusiveVisitRecordDao;

    @Override
    public void saveRecord(ExclusiveVisitRecordParams recordParams) {
        UserData userData = userDataService.lambdaQuery()
                .select(UserData::getId, UserData::getUserId)
                .eq(UserData::getInvitationCode, recordParams.getCode())
                .one();
        if (Objects.isNull(userData)) return;
        recordParams.setUserId(userData.getUserId());
        recordParams.setId(snowflake.nextId());
        int count = exclusiveVisitRecordDao.insertIgore(recordParams);
        if (count == 0) {
            return;
        }
        // 获取城市
        JSONObject ipInfo = IpUtil.getIpInfo(recordParams.getIp());
        userDataService.lambdaUpdate()
                .setSql("exclusive_visit_cnt = exclusive_visit_cnt + 1")
                .set(UserData::getExclusiveVisitTime, new Date())
                .eq(UserData::getId, userData.getId())
                .update();
        try {
            log.info("获取IP信息成功：{}", ipInfo);
            new ExclusiveVisitRecord().setId(recordParams.getId())
                    .setProvince(ipInfo.getString("region"))
                    .setCity(ipInfo.getString("city"))
                    .updateById();
        } catch (Exception ignore){}
    }

    @Override
    public void getListForAdmin(ExclusiveVisitRecordPage page) {
        lambdaQuery().eq(ExclusiveVisitRecord::getUserId, page.getUserId())
                .orderByDesc(ExclusiveVisitRecord::getCreateTime)
                .page(page);
    }
}

